<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class SqlListener
{
    private $filename;
    private $filepath;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        $this->filename = 'sql-'.date('Ymd').'.log';
        $this->filepath = 'logs/sql';
    }

    /**
     * Handle the event.
     *
     * @param QueryExecuted $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        if (config('app.env') === 'local') {
            $sql = str_replace('?', "'%s'", $event->sql);
            $content = vsprintf($sql, $event->bindings);
            $this->addLog($content, $event->time);
        }
    }

    //写入sql日志
    private function addLog($content = '', $executeTime = 0)
    {
        //文件夹不存在则创建
        is_dir(storage_path($this->filepath)) or mkdir(storage_path($this->filepath), 0777, true);
        $content = '['.date('Y-m-d H:i:s').'] '.config('app.env').'.DEBUG: Query:'.$content.', Time:'.$executeTime.'ms'.PHP_EOL;
        try {
            file_put_contents(
                storage_path($this->filepath.'/'.$this->filename),
                $content,
                FILE_APPEND
            );
        } catch (\Exception $err) {
            Log::error('写入SQL文件失败!');
        }
    }
}
